package com.gitee.xzb617.mybatis.sqllog.spring;

import com.gitee.xzb617.mybatis.sqllog.context.ReqContext;
import com.gitee.xzb617.mybatis.sqllog.context.ReqContextHolder;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * 外部请求调用的上下文拦截器
 * @author xuzhibin
 */
public class ReqContextInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        ReqContext context = new ReqContext();
        context.setRequestUri(request.getRequestURI());
        context.setRequestTime(new Date());
        ReqContextHolder.put(context);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ReqContextHolder.remove();
    }

}
